﻿using System;
using System.IO;

namespace VisionCloud.Api.Common
{
    /// <summary>
    /// 字符粗转换
    /// </summary>
    public class Base64ConvertImage
    {
        /// <summary>
        /// 系统根目录
        /// </summary>
        public static string ROOT_PATH { get; set; } = AppDomain.CurrentDomain.BaseDirectory; //DependencyService.Get<IPathManager>().GetgetExternalStorageDirectoryFiles();

        /// <summary>
        /// 将base64格式转换为指定路径图片
        /// </summary>
        /// <param name="path"></param>
        /// <param name="imgName"></param>
        /// <param name="base64Str"></param>
        /// <returns></returns>
        public static string ConvertToImageFromBase64(string path, string imgName, string base64Str)
        {
            string imgPath = string.Empty;

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                imgPath = Path.Combine(path, imgName);

                if (File.Exists(imgPath))
                {
                    //如果已经存在则删除旧图片
                    File.Delete(imgPath);
                }

                if (base64Str.ToLower().Contains("base64"))
                {
                    base64Str = base64Str.Split(',')[1];
                }

                var imgBytes = Convert.FromBase64String(base64Str);

                using (var stream = new FileStream(imgPath, FileMode.Create))
                {
                    stream.Write(imgBytes, 0, imgBytes.Length);
                }
            }
            catch (Exception ex)
            {
                //LogHelper.Error("转换bas64异常", ex);
                throw ex;
            }
            return imgPath;
        }
    }
}